<?php
if (! defined('IN_SITE')) {
	exit('invalid request');
}

/**
 * 应用路由。
 *
 * 建议在 Nginx 做如下配置，以隐藏 url 中的 .php，实现伪静态化：
 *
 *		location /d/ {
 *			rewrite ^\/d\/(\\w+)(\/(\\w+))? /index.php?mod=$1&code=$3 last;
 *		}
 *		location /m {
 *			rewrite ^\/m(\/(\\w+)(\/(\\w+))?)? /admin.php?mod=$2&code=$4 last;
 *		}
 */
class Dispatcher {
	static $modules_root;
	static $types;
	static $defType;
	static public function initTypes($types, $defType)
	{
		self::$modules_root = ROOT_PATH . 'modules/';
		self::$types = $types;
		self::$defType = $defType;
	}

	public function __construct()
	{
	}

	public function run($type = '')
	{
		// 凡是经过 PHP 的响应内容都禁用缓存
		header('Cache-Control: no-cache');

		if (!isset(self::$types[$type])) {
			$type = self::$defType;
		}

		@include_once self::$modules_root . 'master.inc.php';
		if (!class_exists('MasterObject')) {
			exit('modules_root path is invalid');
		}

		$options = self::$types[$type];
		@include_once self::$modules_root . $options['modules_path'] . $this->_init_mod($options) . '.mod.php';
		if (!class_exists('ModuleObject')) {
			exit('mod is invalid');
		}

		new ModuleObject();
	}

	private function _init_mod($options = array())
	{
		$mod = get_param('mod');
		$mod = (empty($mod) ? $options['mod_default'] : $mod);
		return $mod;
	}
}

Dispatcher::initTypes(array(
	'index' => array(
		'modules_path'	=> 'index/',
		'mod_default'	=> 'home',
	),
	'admin' => array(
		'modules_path'	=> 'admin/',
		'mod_default'	=> 'console',
	),
), 'index');
